/**
 * Created by zzy on 2017/2/9.
 */
var shippingStatus = {"new":"新建","sent":"已发货","receiving":"收货中","received":"已收货","shelving":"上架中","shelve":"已上架"};
var shelveStatus = {"new":"未上架","shelving":"上架中","shelve":"已上架"};
var $alert = require("libs/alert");
var fixedW = 4;
var fixedV = 8;
var table2Loaded = false;
require(['jquery','easyui',"libs/confirm","bootstrap","layout/uiJs"],function($){
    $(".header").show();
    $.parser.parse();
    $("#startDt2").datebox({
        editable:false,
        onSelect : function(startDt){
            var arr,reg=new RegExp("(^| )TimeZone=([^;]*)(;|$)");
            var cookieTimeZone;
            var timeZoneOffsetInSeconds;
            if(arr=document.cookie.match(reg)){
                cookieTimeZone = decodeURI(arr[2]).replace(/\"/g,"");
                timeZoneOffsetInSeconds = Date.parse("Thu Jan 01 1970 00:00:00 "+cookieTimeZone+" (GMT)");
            }else{
                cookieTimeZone = null;
                timeZoneOffsetInSeconds  = new Date().getTimezoneOffset() * 60 * 1000;
            }
            var datePart1 = new Date(startDt).format('yyyy-MM-dd');
            var currentSelectDate = datePart1 + " " + "00:00:00";
            var limitDate = new Date(currentSelectDate);
            var dateSeconds = new Date(currentSelectDate.replace(/-/g,"/")).valueOf();
            var utc0 = new Date(dateSeconds + timeZoneOffsetInSeconds).format('yyyy-MM-dd hh:mm:ss');
            $('#startDt2').data('utc0',utc0);
            $('#endDt2').datebox().datebox('calendar').calendar({
                validator: function(endDt){
                    return limitDate<=endDt;
                }
            });
            $('#endDt2').data('utc0','');
        }
    });

    $('#endDt2').datebox({
        editable:false,
        onSelect: function(date){
            var arr,reg=new RegExp("(^| )TimeZone=([^;]*)(;|$)");
            var cookieTimeZone;
            var timeZoneOffsetInSeconds;
            if(arr=document.cookie.match(reg)){
                cookieTimeZone = decodeURI(arr[2]).replace(/\"/g,"");
                timeZoneOffsetInSeconds = Date.parse("Thu Jan 01 1970 00:00:00 "+cookieTimeZone+" (GMT)");
            }else{
                cookieTimeZone = null;
                timeZoneOffsetInSeconds  = new Date().getTimezoneOffset() * 60 * 1000;
            }
            var datePart1 = new Date(date).format('yyyy-MM-dd');
            var currentSelectDate = datePart1 + " " + "23:59:59";
            var dateSeconds = new Date(currentSelectDate.replace(/-/g,"/")).valueOf();
            var utc0 = new Date(dateSeconds + timeZoneOffsetInSeconds).format('yyyy-MM-dd hh:mm:ss');
            $('#endDt2').data('utc0',utc0);
        }
    });

    tableInit();
    $('#tab').tabs({
        onSelect: function(title){
            if(title === '头程自理发货单列表'){
                if(!table2Loaded){
                    table2Init();
                }
            }
        }
    });
    //查询按钮点击事件
    $("#main_search").on("click",function () {
        searchShipNote();
    });
    $("#main_search2").on("click",function () {
        searchSelfCareShipNote();
    });
    //查看配载单详情
    $("body").on("click","a[name=loadNo]",function () {
        loadInfoLoadReadOnly($(this).data('no'));
    });
    //dialog关闭时清空数据
    $('#dialog_loadinfo').on('hidden.bs.modal', function () {
        $("#div_loadinfo_detail_readonly").find('.fill-text').html('');
        $("#load_inroom_order_table_readonly tbody").html('');
    });
    $(document).on('click','a[name=orderDetail]',function () {
        window.parent.tabOpen($(this).attr('ref'),'入库单详情',true,true);
    });
    $(document).on('click','a[name=entDetail]',function () {
        window.parent.tabOpen($(this).attr('ref'),'客户公司',true,true);
    });
    $(document).on('click','a[name=asnCode]',function () {
        window.parent.tabOpen($(this).attr('ref'),'国内仓发货单详情',true,true);
    });
    $(document).on('click','a[name=asnCodeSelf]',function () {
        window.parent.tabOpen($(this).attr('ref'),'头程自理发货单详情',true,true);
    });
});
function loadInfoLoadReadOnly(loadInfoNo) {
    $.ajax({
        url:'api/v1/p/mms/loadInfo/load',
        type:'post',
        data:{
            loadInfoNo:loadInfoNo
        },
        dataType:'json',
        success:function (result) {
            if(result.code == 200){
                var $data = result.data;
                //重新对dialog填充数据
                dialogReloadReadOnly($data);
            }else{
                $alert(result.message);
            }
        }
    })
}
function dialogReloadReadOnly($data){
    var $fillText = $('#div_loadinfo_detail_readonly').find('.fill-text');
    var callback = function (result) {
        if(result.code == 200) {
            var data = result.data.rows;
            var $tbody = $("#load_inroom_order_table_readonly tbody");
            $tbody.html('');
            var rows='';
            $.each(data,function (index,row) {
                rows=rows+"<tr><td style='display: none;'>"+row.orderId+"</td><td>"+row.orderNo+
                    "</td><td>"+row.collectWarehouseName+"</td><td>"+row.toWarehouseName+"</td><td>"+
                    row.logisticsName+"</td><td>"+row.logisticsPlanName+"</td>";
                if(row.cNums==''||row.cNums==null){
                    rows=rows+"<td>"+row.tNums+"</td>";
                }else{
                    rows=rows+"<td>"+row.cNums+"</td>";
                }
                if(row.cWeight==''||row.cWeight==null){
                    rows=rows+"<td>"+Number(row.tWeight).toFixed(fixedW)+"</td>";
                }else{
                    rows=rows+"<td>"+Number(row.cWeight).toFixed(fixedW)+"</td>";
                }
                if(row.cVolumn==''||row.cVolumn==null){
                    rows=rows+"<td>"+Number(row.tVolumn).toFixed(fixedV)+"</td>";
                }else{
                    rows=rows+"<td>"+Number(row.cVolumn).toFixed(fixedV)+"</td>";
                }
                if(row.orderStatus=='commit'){
                    rows=rows+"<td>"+"已提交"+"</td>"
                }else if(row.orderStatus=='c_collect'){
                    rows=rows+"<td>"+"已揽收"+"</td>"
                }else if(row.orderStatus=='c_receive'){
                    rows=rows+"<td>"+"已收货"+"</td>"
                }else if(row.orderStatus=='c_ourtoom'){
                    rows=rows+"<td>"+"集货出库"+"</td>"
                }else if(row.orderStatus=='p_inroom'){
                    rows=rows+"<td>"+"转运入库"+"</td>"
                }else if(row.orderStatus=='p_outroom'){
                    rows=rows+"<td>"+"转运出库"+"</td>"
                }else if(row.orderStatus=='o_inroom'){
                    rows=rows+"<td>"+"海外入库"+"</td>"
                }else if(row.orderStatus=='o_shelve'){
                    rows=rows+"<td>"+"海外入库"+"</td>"
                }else {
                    rows=rows+"<td>"+""+"</td>"
                }
                rows=rows+"<td>"+row.outroomDt+"</td>";
            });
            $tbody.append(rows);
            $('#dialog_loadinfo_readonly').modal("show");
        }else{
            $alert(result.message);
        }
    };
    loadInfoReload($fillText,$data,callback);
}
function loadInfoReload($fillText,$data,callback){
    $fillText.html('');
    $fillText.eq(0).append("<span>"+$data.fromWarehouseName+"</span>");
    $fillText.eq(1).append("<span>"+$data.toWarehouseName+"</span>");
    $fillText.eq(2).append("<span>"+$data.logisticsName+"</span>");
    $fillText.eq(3).append("<span>"+$data.providerCode+"</span>");
    $fillText.eq(4).append("<span>"+$data.logisticsPlanName+"</span>");
    if($data.logisticsType=='A'){
        $fillText.eq(5).append("<span>"+"空运"+"</span>");
    }else{
        $fillText.eq(5).append("<span>"+"海运"+"</span>");
    }
    $fillText.eq(6).append("<span>"+$data.startPort+"</span>");
    $fillText.eq(7).append("<span>"+$data.transferPort+"</span>");
    $fillText.eq(8).append("<span>"+$data.destPort+"</span>");
    $fillText.eq(9).append("<span>"+$data.estimateLeaveDt+"</span>");
    $fillText.eq(10).append("<span>"+$data.estimateArriveDt+"</span>");
    $fillText.eq(11).append("<span>"+$data.tBoxNums+"</span>");
    $fillText.eq(12).append("<span>"+Number($data.tWeight).toFixed(fixedW)+"</span>");
    $fillText.eq(13).append("<span>"+Number($data.tVolumn).toFixed(fixedV)+"</span>");
    if($data.state=='N'){
        $fillText.eq(14).append("<span>"+"新建"+"</span>");
    }else{
        $fillText.eq(14).append("<span>"+"已订舱"+"</span>");
    }
    $.ajax({
        url:'api/v1/p/mms/loadInfo/inRoomOrderList',
        type:'post',
        data:{
            loadInfoId:$data.loadInfoId,
            page:1,
            rows:100
        },
        dataType:'json',
        success:callback
    });
}
function tableInit() {
    $("#main_table").datagrid({
        url:'api/v1/p/wms/shipping/note/list',
        border : false,
        height:$(window).height(),
        pagination : true,
        idField : 'id',
        pageSize : 20,
        pageList : [ 20, 50,  100 ],
        rownumbers:true,
        singleSelect: true,
        emptyMsg : "暂无数据",
        rowStyler: function (index, row) {
            if(!row.receiveDt){
                var time = (new Date()).valueOf() - (new Date(row.estimatedDt)).valueOf();
                if(time >= 0){
                    return {class:'red-font'};
                }
            }
        },
        queryParams:{
            queryType: 'shipping'
        },
        columns:[[ {
            field : 'code',
            title : '发货单编号',
            formatter: function(value,row,index){
                return "<a name='asnCode' href='javascript:;' ref='ship-note-detail?noteCode="+value+"&asnId="+row.id+"'>"+value+"</a>";
            }
        },{
            field : 'loadNo',
            title : '配载单号',
            formatter:function (value,row,index) {
                return "<a href='javascript:;' name='loadNo' data-no='"+value+"'>"+value+"</a>"
            }
        },{
            field : 'startWarehouse',
            title : '发货仓'
        },{
            field : 'destWarehouse',
            title : '海外仓'
        },{
            field:'shippingStatus',
            title:'发货状态',
            width:'5%',
            formatter: function(value,row,index){
                return shippingStatus[value];
            }
        },{
            field:'shelveStatus',
            title:'上架状态',
            width:'5%',
            formatter: function(value,row,index){
                return shelveStatus[value];
            }
        },{
            field:'totalNum',
            title:'总件数'
        },{
            field:'fNum',
            title:'实收件数'
        },{
            field:'totalOrderNum',
            title:'总订单数',
            width:'5%'
        },{
            field:'totalBoxNum',
            title:'总包裹数'
        },{
            field:'totalGoodsNum',
            title:'实收商品件数'
        },{
            field:'totaolGoodsShelveNum',
            title:'已上架商品件数'
        },{
            field:'deliveryDt',
            title:'发货时间'
        },{
            field:'estimatedDt',
            title:'预计到货时间'
        },{
            field:'receiveDt',
            title:'实际收货时间'
        }
        ]],
        loadFilter:function(data){
            if(data.code=='200'){
                return data.data;
            }else{
                return [];
            }
        },
        toolbar:"#tb"
    });
}
function table2Init() {
    table2Loaded = true;
    $("#main_table2").datagrid({
        url:'api/v1/p/wms/shipping/note/shelfCareList',
        border : false,
        height:$(window).height(),
        pagination : true,
        idField : 'id',
        pageSize : 20,
        pageList : [ 20, 50,  100 ],
        rownumbers:true,
        singleSelect: true,
        emptyMsg : "暂无数据",
        rowStyler: function (index, row) {
            if(!row.receiveDt){
                var time = (new Date()).valueOf() - (new Date(row.estimatedDt)).valueOf();
                if(time >= 0){
                    return {class:'red-font'};
                }
            }
        },
        columns:[[ {
            field : 'code',
            title : '发货单编号',
            formatter: function(value,row,index){
                return "<a name='asnCodeSelf' href='javascript:;' ref='ship-note-self-detail?noteCode="+value+"&asnId="+row.id+"'>"+value+"</a>";
            }
        },{
            field : 'orderNo',
            title : '入库单号',
            formatter:function (value,row,index) {
                return "<a href='javascript:;' ref='in-order-detail?id="+row.orderId+"&self=Y' name='orderDetail' data-no='"+value+"'>"+value+"</a>"
            }
        },{
            field : 'entName',
            title : '客户名称',
            formatter:function (value,row,index) {
                return "<a class='ellipsis' href='javascript:;' ref='company-detail?id="+row.entId+"' name='entDetail' title='"+value+"'>"+value+"</a>";
            }
        },{
            field : 'destWarehouse',
            title : '海外仓'
        },{
            field:'shippingStatus',
            title:'发货状态',
            formatter: function(value,row,index){
                if(value=='sent'){
                    return '已提交';
                }
                return shippingStatus[value];
            }
        },{
            field:'shelveStatus',
            title:'上架状态',
            width:'5%',
            formatter: function(value,row,index){
                return shelveStatus[value];
            }
        },{
            field:'totalBoxNum',
            title:'总包裹数'
        },{
            field:'totalGoodsNum',
            title:'预报商品件数'
        },{
            field:'totaolGoodsShelveNum',
            title:'已上架商品件数'
        },{
            field:'commitDt',
            title:'提交时间'
        },{
            field:'estimatedDt',
            title:'预计到货时间'
        },{
            field:'receiveDt',
            title:'实际收货时间'
        }
        ]],
        loadFilter:function(data){
            if(data.code=='200'){
                return data.data;
            }else{
                return [];
            }
        },
        toolbar:"#tb2"
    });
}
function searchShipNote() {
    var d1 = $('#wareshouse-care #startDt').datebox('getValue');
    var d2 = $('#wareshouse-care #endDt').datebox('getValue');
    $('#main_table').datagrid('load',{
        code:$('#code').val(),
        loadNo:$('#loadNo').val(),
        orderNo:$('#orderNo').val(),
        shippingStatus:$('#status').combobox('getValue'),
        shelveStatus:$('#shelveStatus').combobox('getValue'),
        startDt:d1?$('#wareshouse-care #startDt').data('utc0'):'',
        endDt:d2?$('#wareshouse-care #endDt').data('utc0'):'',
        queryType: 'shipping'
    });
}
function searchSelfCareShipNote() {
    $('#main_table2').datagrid('load',{
        code:$('#code2').val(),
        orderNo:$('#orderNo2').val(),
        shippingStatus:$('#shippingStatus2').combobox('getValue'),
        shelveStatus:$('#shelveStatus2').combobox('getValue'),
        commitDtFrom:$('#startDt2').data('utc0'),
        commitDtTo:$('#endDt2').data('utc0')
    });
}